package com.lfd.mqttv3.mqtt;

import com.lfd.mqttv3.properties.MqttProperties;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @项目名： spring-emq
 * @包名： com.lfd.mqttv3.mqtt
 * @文件名: MqttSubscriber
 * @创建者: liufudong@szyh-smart.com
 * @创建时间: 2024/10/5 14:22
 * @描述：
 */
@Slf4j
@Component
public class MqttSubscriber {
    @Autowired
    private MqttProperties mqttProperties;

    public void subscribe(String topic) throws MqttException {
        // 创建MQTT客户端
        MqttClient client = new MqttClient(
                mqttProperties.getBrokerUrl(),
                mqttProperties.getClientId()
        );
        log.info("MqttSubscriber to BrokerUrl: {}", mqttProperties.getBrokerUrl());
        log.info("MqttSubscriber to ClientId: {}", mqttProperties.getClientId());
        // 创建连接选项
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setUserName(mqttProperties.getUsername());
        // 设置密码，必须是字符数组
        mqttConnectOptions.setPassword(mqttProperties.getPassword().toCharArray());

        //设置回调
        client.setCallback(new MqttCallback() {
            @Override
            public void connectionLost(Throwable throwable) {
                log.info("MqttSubscriber connectionLost Throwable", throwable);
            }

            @Override
            public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
                String msg = new String(mqttMessage.getPayload());
                int id = mqttMessage.getId();
                int qos = mqttMessage.getQos();
                log.info("MqttSubscriber messageArrived 主题:{},消息内容:{},id:{},qos:{}", s, msg, id, qos);
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
                log.info("MqttSubscriber deliveryComplete Delivery complete ");
            }
        });
        // 使用带有认证信息的选项连接到MQTT服务器
        client.connect(mqttConnectOptions);
//        // 连接到MQTT服务器
//        client.connect();
        // 阅主题 qos等级2
        client.subscribe(topic,2);
    }
}
